#ifndef _LOGIC_H_
#define _LOGIC_H_

#include <iostream>
#include <map>
#include "netserver.h"
#include "netclient.h"
#include "mpool.h"
#include "bs_def.h"

#define LOGIC_DEF_OVERTIME      60

class LogicServer{
    public:
        LogicServer(){
            //client.Connet(ip, port);
            //server.Listen(port);
        }

        LogicServer(int port):m_server(port){
            m_overtime = LOGIC_DEF_OVERTIME;
            m_is_server = true;
            m_is_client = false;
        }

        LogicServer(const char* dataip, int dataport, int port):m_client(dataip, dataport),m_server(port){
            memcpy(dbip, dataip, BS_DEF_STRLEN);
            dbip[BS_DEF_STRLEN-1] = '\0';
            dbport = dataport;
            m_overtime = LOGIC_DEF_OVERTIME;
            m_is_server = true;
            m_is_client = true;
        }

        /**
         * 主执行函数
         */
        void run();
        virtual void handle(void* arg) = 0;
        inline int getSocketMap(pthread_t thread){return m_socket_map[thread];}
        inline bool delSocketMap(pthread_t thread){
            std::map<pthread_t, int>::iterator iter = m_socket_map.find(thread);
            if(iter!= m_socket_map.end()){
                m_socket_map.erase(iter);
                return true;
            }
            return false;
        }
        inline const char* getDBIp(){return dbip;}
        inline int getDBPort(){return dbport;}
        inline bool isConnectServer(){return m_client.isConnected();}
        inline void connectServer(){ m_client.Connect(dbip, dbport);}
        inline int getOvertime(){return m_overtime;}

        const static int STREAM_BUF_SIZE = 1024000;
    protected:
        // 本程序为server端超时时间
        int             m_overtime;
        // 本程序为client端连接的server端
        char            dbip[BS_DEF_STRLEN];
        int             dbport;

        std::map<pthread_t, int> m_socket_map;  // threadid到socket的映射
        NetServer       m_server; //该Logic为server
        NetClient       m_client; //该logic为client，相对与dbserver

        bool            m_is_server;
        bool            m_is_client;
};

#endif
